package com.zoe.onelink.feign.auth.aspect;

import com.zoe.onelink.annotation.web.rpc.InnerApi;
import com.zoe.onelink.common.constant.OnelinkFeignConstant;
import com.zoe.onelink.common.enumeration.ExceptionCodeEnum;
import com.zoe.onelink.common.exception.ApiException;
import com.zoe.onelink.feign.auth.token.FeignTokenValidator;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-02-28
 */
@Aspect
@RequiredArgsConstructor
public class FeignInnerApiAspect {


    private final HttpServletRequest request;
    private final FeignTokenValidator validator;

    @Around("@within(innerApi) || @annotation(innerApi)")
    public Object aspect(ProceedingJoinPoint joinPoint, InnerApi innerApi) throws Throwable {
        // 获取Feign内部Token
        String feignToken = this.request.getHeader(OnelinkFeignConstant.TOKEN_HEADER_NAME);
        // 验证Token是否有效
        if (this.validator != null && !this.validator.validate(feignToken)) {
            throw ApiException.createEx(ExceptionCodeEnum.RPC_TOKEN_NOT_VALID);
        }
        return joinPoint.proceed();
    }

}
